package com.mall.czlr.base.interceptor;

import com.mall.czlr.base.annotation.Login;
import com.mall.czlr.base.exception.BaseException;
import com.mall.czlr.base.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URI;

@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {
    private final Authenticator authenticator;

    @Autowired
    public SecurityInterceptor(Authenticator authenticator) {
        this.authenticator = authenticator;
    }

    private static String[] GUEST_URI = {"/swagger-ui.html", "/configuration/ui", "/swagger-resources", "/csrf", "/error", "/webjars"};

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        URI uri = new URI(httpServletRequest.getRequestURI());
        String path = uri.getPath();

        // 如果是游客链接直接跳过
        for (String guestUri : GUEST_URI) {
            if (path.contains(guestUri)) {
                return true;
            }
        }

//        log.trace("=======>");
//        log.trace("path: {}", path);
//        log.trace("query: {}", httpServletRequest.getQueryString());
//        log.trace("parameter: ");
//        if (!(httpServletRequest instanceof MultipartHttpServletRequest)) {
//            httpServletRequest.getParameterMap().forEach((key, value) -> log.trace("{}: {}", key, value));
//        }
//        log.trace("<=======");

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Login login = method.getAnnotation(Login.class);
            if (login == null || login.needToken()) {
                // 如果注解为null 或者需要token, 说明需要拦截
                authenticator.process(httpServletRequest);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public interface Authenticator {
        void process(HttpServletRequest httpServletRequest);
    }

    public static String getRequiredParam(HttpServletRequest httpServletRequest, String key) {
        if (!httpServletRequest.getParameterMap().containsKey(key)) {
            throw new GlobalException(BaseException.ERROR_PARAM_NOT_SET, key + " not set");
        }

        return httpServletRequest.getParameter(key);
    }
}
